import Platform from '../entities/Platform.js';
import Carrot from '../entities/Carrot.js';
import Boss from '../entities/Boss.js';
import Settings from '../config/Settings.js';
import Enemy from '../entities/Enemy.js';
import Powerup from '../entities/PowerUp.js';

export default class LevelManager {
  constructor(game) {
    this.game = game;
    
    this.platforms = [];
    this.carrots = [];
    this.boss = null;
    
    this.currentLevel = 1;
    this.levelTimer = 0;
    this.bossWarning = false;
    
    this.carrotTimer = 0;
    this.enemies = [];
    this.enemyTimer = 0;
    
    this.pausePlatformGeneration = false;
    
    this.powerUps = [];
    
    // 关卡进度跟踪
    this.distanceTraveled = 0;
    this.enemiesDefeated = 0;
    this.secretsFound = 0;
    this.maxCombo = 0;
    
    // 关卡主题和目标
    this.currentTheme = null;
    this.objectives = [];
    this.objectivesCompleted = false;
    
    // 背景过渡效果
    this.backgroundTransition = null;
  }
  
  init() {
    // 初始化第一个关卡主题
    this.setCurrentTheme(0);
    
    // 初始化关卡目标
    this.initLevelObjectives();
    
    // 创建初始平台
    const initialPlatform = new Platform(this.game, {
      x: this.game.canvas.width / 8,
      y: this.game.canvas.height - 100,
      width: 300,
      type: 'normal'
    });
    
    this.platforms.push(initialPlatform);
  }
  
  // 设置当前主题
  setCurrentTheme(themeIndex) {
    const themeConfig = Settings.level.themes[themeIndex % Settings.level.themes.length];
    this.currentTheme = themeConfig;
    
    // 设置背景过渡效果
    if (this.game.backgroundColor !== themeConfig.backgroundColor) {
      this.backgroundTransition = {
        from: this.game.backgroundColor || '#87CEEB',
        to: themeConfig.backgroundColor,
        progress: 0,
        speed: 0.02
      };
    }
    
    // 更新游戏状态
    this.game.backgroundColor = themeConfig.backgroundColor;
    this.game.groundColor = themeConfig.groundColor;
    
    // 更新背景元素主题
    if (this.game.backgroundManager) {
      this.game.backgroundManager.setTheme(themeConfig);
    }
    
    console.log(`关卡主题设置为: ${themeConfig.name}`);
  }
  
  // 初始化关卡目标
  initLevelObjectives() {
    if (!this.currentTheme || !this.currentTheme.objectives) return;
    
    this.objectives = this.currentTheme.objectives.map(obj => ({
      type: obj.type,
      target: obj.value,
      current: 0,
      description: obj.description,
      completed: false
    }));
    
    this.objectivesCompleted = false;
    console.log('关卡目标初始化完成:', this.objectives);
  }
  
  update() {
    // 增加关卡时间
    this.levelTimer++;
    
    // 增加行进距离 (每帧增加距离)
    this.distanceTraveled += Settings.platform.speed / 10;
    
    // 更新背景过渡
    this.updateBackgroundTransition();
    
    // 更新平台
    for (let i = this.platforms.length - 1; i >= 0; i--) {
      const platform = this.platforms[i];
      const shouldRemove = platform.update();
      
      // 移除超出屏幕的平台或需要移除的特殊平台
      if (platform.isOffScreen() || shouldRemove) {
        this.platforms.splice(i, 1);
      }
    }
    
    // 创建新平台
    if (this.platforms.length < 5 && !this.pausePlatformGeneration) {
      const lastPlatform = this.platforms[this.platforms.length - 1];
      if (!lastPlatform || lastPlatform.x < this.game.canvas.width - 300) {
        this.createPlatform();
        
        // 随机生成秘密区域
        if (Math.random() < 0.1 && this.platforms.length > 5) {
          this.createSecretArea();
        }
      }
    }
    
    // 更新胡萝卜
    this.updateCarrots();
    
    // 更新连击计数
    this.updateCombo();
    
    // 确保首先应用玩家的垂直移动（如果玩家和游戏状态有效）
    if (this.game.player && this.game.state === 'running') {
      // 记录之前的位置和状态，用于调试
      const prevY = this.game.player.y;
      const prevOnGround = this.game.player.onGround;
      
      // 应用重力前，先确保玩家下一状态已确定
      if (!this.game.player.onGround) {
        // 如果玩家不在地面上，预先更新垂直速度（应用重力）
        // 注意：在Player的update方法中，我们也会这样做，但是这里是为了确保
        const isBossFight = this.currentBoss != null;
        const currentSettings = isBossFight ? Settings.player.bossMode : Settings.player;
        
        // 只有在还没有达到终极下落速度时应用重力
        if (this.game.player.verticalVelocity < 15) { // 15是最大下落速度
          this.game.player.verticalVelocity += currentSettings.gravity;
        }
      }
      
      // 更新玩家Y坐标（应用垂直速度）
      this.game.player.y += this.game.player.verticalVelocity;
      
      // 检测平台碰撞，此方法会更新玩家的onGround状态
      this.checkPhysics();
      
      // 如果玩家状态改变，记录日志
      if (prevOnGround !== this.game.player.onGround) {
        console.log('Player ground state changed:', {
          from: prevOnGround ? 'on ground' : 'in air',
          to: this.game.player.onGround ? 'on ground' : 'in air',
          prevY: prevY,
          currentY: this.game.player.y,
          verticalVelocity: this.game.player.verticalVelocity
        });
      }
      
      // 每60帧输出一次垂直位置更新信息
      if (this.game.gameTime % 60 === 0) {
        console.log('Player physics update:', {
          positionY: this.game.player.y,
          verticalVelocity: this.game.player.verticalVelocity,
          onGround: this.game.player.onGround,
          platformCount: this.platforms.length,
          nearbyPlatforms: this.platforms
            .filter(p => Math.abs(p.y - (this.game.player.y + this.game.player.height)) < 50)
            .map(p => ({x: p.x, y: p.y, type: p.type}))
        });
      }
    }
    
    // 更新Boss
    if (this.boss) {
      this.updateBoss();
    } else {
      // 检查是否应该生成Boss
      this.checkBossSpawn();
    }
    
    // 更新敌人
    this.updateEnemies();
    
    // 更新道具
    this.updatePowerUps();
    
    // 更新关卡目标
    this.updateObjectives();
  }
  
  // 更新背景过渡效果
  updateBackgroundTransition() {
    if (!this.backgroundTransition) return;
    
    this.backgroundTransition.progress += this.backgroundTransition.speed;
    
    if (this.backgroundTransition.progress >= 1) {
      this.game.backgroundColor = this.backgroundTransition.to;
      this.backgroundTransition = null;
    } else {
      // 计算过渡色
      const p = this.backgroundTransition.progress;
      const from = this.hexToRgb(this.backgroundTransition.from);
      const to = this.hexToRgb(this.backgroundTransition.to);
      
      const r = Math.floor(from.r + (to.r - from.r) * p);
      const g = Math.floor(from.g + (to.g - from.g) * p);
      const b = Math.floor(from.b + (to.b - from.b) * p);
      
      this.game.backgroundColor = `rgb(${r},${g},${b})`;
    }
  }
  
  // 将十六进制颜色转换为RGB对象
  hexToRgb(hex) {
    // 移除#前缀（如果有）
    hex = hex.replace(/^#/, '');
    
    // 解析RGB值
    let bigint = parseInt(hex, 16);
    let r = (bigint >> 16) & 255;
    let g = (bigint >> 8) & 255;
    let b = bigint & 255;
    
    return { r, g, b };
  }
  
  createPlatform() {
    // 确定平台类型
    const platformTypes = Settings.platform.types;
    const platformTypesList = Object.entries(platformTypes)
      .filter(([key, data]) => data.chance > 0)  // 只考虑有概率的类型
      .sort((a, b) => b[1].chance - a[1].chance);  // 按概率排序
    
    let randomValue = Math.random();
    let cumulativeChance = 0;
    let selectedType = 'normal';  // 默认类型
    
    for (const [type, data] of platformTypesList) {
      cumulativeChance += data.chance;
      if (randomValue <= cumulativeChance) {
        selectedType = type;
        break;
      }
    }
    
    // 确定平台宽度
    const platformWidth = platformTypes[selectedType].width || Settings.platform.width;
    
    // 计算水平位置 - 确保在可见区域之外生成
    let lastPlatformX = this.game.canvas.width;
    let lastPlatformY = this.game.canvas.height / 2;  // 默认值
    
    if (this.platforms.length > 0) {
      const lastPlatform = this.platforms[this.platforms.length - 1];
      lastPlatformX = lastPlatform.x + lastPlatform.width;
      lastPlatformY = lastPlatform.y;
    }
    
    // 添加随机间距
    const gapX = Settings.platform.gap.min + 
      Math.random() * (Settings.platform.gap.max - Settings.platform.gap.min);
    const x = lastPlatformX + gapX;
    
    // 计算垂直位置 - 确保平台不会太高或太低，且与前一个平台的高度差不会太大
    const minY = Settings.platform.minY;
    const maxY = Settings.platform.maxY;
    
    // 垂直位置变化不要太大
    const maxVerticalChange = Settings.platform.maxGapY;
    
    let minPossibleY = Math.max(minY, lastPlatformY - maxVerticalChange);
    let maxPossibleY = Math.min(maxY, lastPlatformY + maxVerticalChange);
    
    // 添加一个偏好因子，让平台更容易出现在屏幕中部
    const centerPreferenceY = this.game.canvas.height / 2;
    const centerBias = 0.7; // 向中心偏移的因子，0-1之间
    
    // 最终的垂直位置是一个加权平均
    let y = minPossibleY + Math.random() * (maxPossibleY - minPossibleY);
    y = y * (1 - centerBias) + centerPreferenceY * centerBias;
    
    // 确保第一个平台不会太高
    if (this.platforms.length === 0) {
      y = Math.min(y, this.game.canvas.height * 0.7);
    }
    
    // 创建平台
    const platform = new Platform(this.game, {
      x,
      y,
      width: platformWidth,
      type: selectedType
    });
    
    this.platforms.push(platform);
    
    // 随机在平台上生成胡萝卜
    if (Math.random() < 0.3) {
      this.createCarrotAbovePlatform(platform);
    }
    
    // 调试信息
    if (this.game.debugMode) {
      console.log('创建平台', {
        type: selectedType,
        x,
        y,
        width: platformWidth,
        height: platform.height,
        gapFromLast: gapX
      });
    }
    
    return platform;
  }
  
  // 创建秘密区域
  createSecretArea() {
    const lastPlatform = this.platforms[this.platforms.length - 1];
    let secretX = lastPlatform.x + 100;
    let secretY = lastPlatform.y;
    
    // 创建一系列向上的平台，通向隐藏区域
    for (let i = 0; i < 3; i++) {
      const secretPlatform = new Platform(this.game, {
        x: secretX,
        y: secretY - 70 * (i + 1),
        width: 60,
        type: 'secret'
      });
      
      this.platforms.push(secretPlatform);
      secretX += 70;
    }
    
    // 在秘密区域末端添加特殊奖励
    const rewardType = Math.random() < 0.3 ? 'shield' : 'doublePoints';
    this.powerUps.push(new Powerup(
      this.game,
      rewardType,
      secretX,
      secretY - 230
    ));
    
    // 增加秘密区域计数
    this.secretsFound++;
    
    console.log('生成了秘密区域');
  }
  
  updateCarrots() {
    // 更新现有胡萝卜
    for (let i = this.carrots.length - 1; i >= 0; i--) {
      const carrot = this.carrots[i];
      carrot.update();
      
      // 移除离开屏幕的胡萝卜
      if (carrot.isOffScreen()) {
        this.carrots.splice(i, 1);
        continue;
      }
      
      // 检查与玩家的碰撞
      if (carrot.checkCollision(this.game.player)) {
        const points = carrot.collect();
        this.game.scoreManager.addScore(points);
        this.game.scoreManager.addCarrot();
        
        // 更新连击系统
        this.updateCombo();
        
        // 播放收集音效
        // if (this.game.audio) this.game.audio.play('carrot');
      }
    }
    
    // 定时生成胡萝卜，根据当前主题调整生成概率
    this.carrotTimer++;
    const spawnInterval = this.currentTheme?.carrotDensity 
      ? Math.max(10, Math.floor(Settings.carrot.spawnInterval / this.currentTheme.carrotDensity))
      : Settings.carrot.spawnInterval;
      
    if (this.carrotTimer >= spawnInterval) {
      this.carrotTimer = 0;
      
      // 随机决定是否生成胡萝卜
      if (Math.random() < 0.5 && !this.boss) {
        this.createRandomCarrot();
      }
    }
  }
  
  createRandomCarrot() {
    // 在屏幕右侧随机位置创建胡萝卜
    const minY = 100;
    const maxY = this.game.canvas.height - 150;
    const y = Math.random() * (maxY - minY) + minY;
    
    // 选择胡萝卜阵型
    const patterns = Object.entries(Settings.carrot.patterns);
    const totalPatternChance = patterns.reduce((sum, [_, config]) => sum + config.chance, 0);
    let random = Math.random() * totalPatternChance;
    let selectedPattern = 'single';
    
    for (const [pattern, config] of patterns) {
      random -= config.chance;
      if (random <= 0) {
        selectedPattern = pattern;
        break;
      }
    }
    
    // 创建胡萝卜阵型
    const newCarrots = Carrot.createPattern(
      this.game,
      selectedPattern,
      this.game.canvas.width,
      y
    );
    
    this.carrots.push(...newCarrots);
  }
  
  // 添加连击系统
  updateCombo() {
    const now = this.game.gameTime;
    
    if (!this.lastCarrotCollectTime || 
        now - this.lastCarrotCollectTime > Settings.carrot.combos.timeWindow) {
      // 重置连击
      this.currentCombo = 1;
    } else {
      // 增加连击数
      this.currentCombo++;
      
      // 更新最大连击数
      if (this.currentCombo > this.maxCombo) {
        this.maxCombo = this.currentCombo;
      }
      
      // 检查是否达到新的连击等级
      for (const multiplier of Settings.carrot.combos.multipliers) {
        if (this.currentCombo === multiplier.count) {
          // 显示连击提示
          this.game.floatingTexts.push({
            content: `${this.currentCombo}连击！x${multiplier.multiplier}`,
            x: this.game.player.x,
            y: this.game.player.y - 70,
            color: '#FFD700',
            alpha: 1,
            velocity: -2
          });
          break;
        }
      }
    }
    
    this.lastCarrotCollectTime = now;
  }
  
  updateBoss() {
    if (!this.boss) return;
    
    this.boss.update();
    
    // 检查玩家与Boss的碰撞
    if (this.checkBossCollision()) {
      // 玩家跳到Boss头上
      if (this.game.player.verticalVelocity > 0 && 
          this.game.player.y + this.game.player.height < this.boss.y + this.boss.height / 2) {
        
        const bossDefeated = this.boss.takeDamage();
        this.game.player.verticalVelocity = -10; // 反弹
        
        if (bossDefeated) {
          this.game.scoreManager.addScore(1000);
          this.boss = null;
          this.nextLevel();
        }
      } else {
        // 玩家受伤
        this.game.player.takeDamage();
      }
    }
  }
  
  checkBossCollision() {
    if (!this.boss) return false;
    
    return (
      this.game.player.x + this.game.player.width / 3 > this.boss.x &&
      this.game.player.x - this.game.player.width / 3 < this.boss.x + this.boss.width &&
      this.game.player.y < this.boss.y + this.boss.height &&
      this.game.player.y + this.game.player.height > this.boss.y
    );
  }
  
  checkBossSpawn() {
    // 如果所有目标已完成，或者已经超过时间，准备Boss战
    if (!this.objectivesCompleted && 
        this.levelTimer >= Settings.level.duration && 
        !this.bossWarning && 
        this.currentTheme?.bossType) {
      // 显示Boss警告
      this.bossWarning = true;
    }
    
    // Boss警告后等待一段时间再生成Boss
    if (this.bossWarning && 
        (this.objectivesCompleted || 
         this.levelTimer >= Settings.level.duration + Settings.level.bossWarningTime)) {
      this.spawnBoss();
    }
  }
  
  spawnBoss() {
    this.bossWarning = false;
    
    // 在屏幕右侧生成Boss
    this.boss = new Boss(this.game);
    
    // 清除所有普通怪物
    this.enemies = [];
    
    // 暂停生成新的平台和胡萝卜
    this.pausePlatformGeneration = true;
  }
  
  // 更新关卡目标
  updateObjectives() {
    if (!this.objectives.length) return;
    
    // 更新每个目标的进度
    let allCompleted = true;
    
    for (const objective of this.objectives) {
      if (objective.completed) continue;
      
      switch(objective.type) {
        case 'distance':
          objective.current = Math.min(objective.target, Math.floor(this.distanceTraveled));
          break;
          
        case 'collect':
          objective.current = Math.min(objective.target, this.game.scoreManager.getCarrots());
          break;
          
        case 'defeat':
          objective.current = Math.min(objective.target, this.enemiesDefeated);
          break;
          
        case 'combo':
          objective.current = Math.min(objective.target, this.maxCombo);
          break;
          
        case 'boss':
          if (this.boss) {
            objective.current = this.boss.health <= 0 ? 1 : 0;
          }
          break;
      }
      
      // 检查是否完成
      if (objective.current >= objective.target) {
        if (!objective.completed) {
          objective.completed = true;
          // 显示目标完成提示
          this.game.floatingTexts.push({
            content: `目标完成: ${objective.description}!`,
            x: this.game.canvas.width / 2,
            y: this.game.canvas.height / 3,
            color: '#00FF00',
            alpha: 1,
            velocity: -1,
            duration: 120
          });
          
          // 奖励积分
          this.game.scoreManager.addScore(100);
        }
      } else {
        allCompleted = false;
      }
    }
    
    // 检查是否所有目标都已完成
    if (allCompleted && !this.objectivesCompleted) {
      this.objectivesCompleted = true;
      // 如果有Boss，触发Boss生成
      if (this.currentTheme?.bossType && !this.boss) {
        this.bossWarning = true;
      } else if (!this.currentTheme?.bossType) {
        // 如果没有Boss，直接进入下一关
        this.nextLevel();
      }
    }
  }
  
  nextLevel() {
    this.currentLevel++;
    
    // 显示关卡完成提示
    this.game.floatingTexts.push({
      content: `关卡 ${this.currentLevel - 1} 完成!`,
      x: this.game.canvas.width / 2,
      y: this.game.canvas.height / 2,
      color: '#FFA500',
      alpha: 1,
      velocity: -0.5,
      duration: 180,
      scale: 2
    });
    
    // 增加难度
    if (this.currentLevel <= Settings.level.totalLevels) {
      // 设置新的关卡主题
      this.setCurrentTheme(this.currentLevel - 1);
      
      // 初始化新关卡的目标
      this.initLevelObjectives();
      
      // 重置关卡进度数据
      this.resetLevelProgress();
      
      // 增加平台移动速度
      Settings.platform.speed += Settings.level.difficultyIncrease.speed;
      
      // 减少平台间距
      if (Settings.platform.gap.min > 100) {
        Settings.platform.gap.min -= Settings.level.difficultyIncrease.gapDecrease;
        Settings.platform.gap.max -= Settings.level.difficultyIncrease.gapDecrease;
      }
    } else {
      // 通关
      this.game.victory();
    }
    
    // 重置关卡计时器
    this.levelTimer = 0;
    this.bossWarning = false;
    this.pausePlatformGeneration = false;
  }
  
  // 重置关卡进度数据
  resetLevelProgress() {
    this.distanceTraveled = 0;
    this.enemiesDefeated = 0;
    this.secretsFound = 0;
    this.maxCombo = 0;
  }
  
  checkPhysics() {
    // 检查玩家与平台的碰撞
    let onPlatform = false;
    let platformAppliedEffect = false;
    let standingPlatform = null;
    
    // 先排序平台，确保最上面的平台先检测
    const sortedPlatforms = [...this.platforms].sort((a, b) => a.y - b.y);
    
    // 记录玩家状态，用于调试
    const prevPlayerY = this.game.player.y;
    const prevOnGround = this.game.player.onGround;
    
    for (const platform of sortedPlatforms) {
      // 使用平台的isPlayerAbove方法检测玩家是否在平台上方
      if (platform.isPlayerAbove(this.game.player)) {
        // 玩家站在平台上，精确定位到平台顶部
        this.game.player.y = platform.y - this.game.player.height;
        this.game.player.verticalVelocity = 0;
        this.game.player.jumpCount = 0; // 重置跳跃次数
        this.game.player.onGround = true; // 确保设置为在地面上
        onPlatform = true;
        standingPlatform = platform;
        
        // 创建小粒子效果以增强"站立"的视觉反馈
        if (this.game.gameTime % 5 === 0) {
          this.game.particleSystem.createParticles(
            this.game.player.x,
            platform.y,
            '#FFFFFF',
            5,  // 增加粒子数量
            2,  // 增加散布范围
            2,
            10
          );
        }
        
        // 输出调试信息
        if (this.game.gameTime % 30 === 0) {
          console.log('玩家站在平台上:', {
            platformType: platform.type,
            platformY: platform.y,
            playerY: this.game.player.y,
            playerBottomY: this.game.player.y + this.game.player.height,
            gap: (this.game.player.y + this.game.player.height) - platform.y
          });
        }
        
        // 应用平台特殊效果
        platformAppliedEffect = platform.applyEffect(this.game.player);
        
        // 如果平台已经处理了弹跳，则不需要继续检测
        if (platformAppliedEffect) break;
      }
    }
    
    // 检查玩家是否站在地面上
    const ground = this.game.canvas.height - 100;  // 将地面位置提高，距离底部100像素
    if (this.game.player.y + this.game.player.height >= ground) {
      this.game.player.y = ground - this.game.player.height;
      this.game.player.verticalVelocity = 0;
      this.game.player.onGround = true;
      this.game.player.jumpCount = 0;
      onPlatform = true;
    } else if (!onPlatform) {
      // 如果不在任何平台上，标记为空中状态
      this.game.player.onGround = false;
    }
    
    // 记录状态变化，用于调试
    if (prevOnGround !== this.game.player.onGround) {
      console.log('玩家状态变化:', {
        从: prevOnGround ? '地面' : '空中',
        到: this.game.player.onGround ? '地面' : '空中',
        位置变化: {
          之前: prevPlayerY,
          之后: this.game.player.y,
          差值: this.game.player.y - prevPlayerY
        },
        垂直速度: this.game.player.verticalVelocity
      });
    }
    
    // 如果玩家站在平台上，在平台与玩家之间绘制一个"关系线"用于调试
    if (standingPlatform && this.game.debugMode) {
      this.standingPlatform = standingPlatform;
    } else {
      this.standingPlatform = null;
    }
    
    // 检查玩家与Boss的碰撞
    if (this.boss) {
      // 检查玩家是否从上方跳到Boss头上
      if (this.game.player.verticalVelocity > 0 && // 玩家正在下落
          this.game.player.y + this.game.player.height >= this.boss.y - 20 && 
          this.game.player.y < this.boss.y + this.boss.height/2 && 
          this.game.player.x + this.game.player.width/2 >= this.boss.x - 20 && 
          this.game.player.x - this.game.player.width/2 <= this.boss.x + this.boss.width + 20) { 
        
        // 玩家跳到Boss头上，造成伤害
        const bossDefeated = this.boss.takeDamage();
        
        // 降低反弹高度
        this.game.player.verticalVelocity = -12; // 从-18改为-12，与普通跳跃高度相近
        
        if (bossDefeated) {
          this.game.scoreManager.addScore(500);
          this.boss = null;
          this.nextLevel();
        }
      }
      // 检查Boss是否撞到玩家（从侧面或下方）
      else if (!this.boss.invincibleTimer && 
               this.game.player.x + this.game.player.width/3 >= this.boss.x &&
               this.game.player.x - this.game.player.width/3 <= this.boss.x + this.boss.width &&
               this.game.player.y + this.game.player.height >= this.boss.y &&
               this.game.player.y <= this.boss.y + this.boss.height) {
        
        // 玩家受伤
        this.game.player.takeDamage();
      }
    }
  }
  
  updateEnemies() {
    // 更新现有敌人
    for (let i = this.enemies.length - 1; i >= 0; i--) {
      const enemy = this.enemies[i];
      enemy.update();
      
      // 检查碰撞
      const collisionResult = enemy.checkCollision(this.game.player);
      if (collisionResult === 'defeat') {
        // 玩家从上方击败敌人
        this.enemies.splice(i, 1);
        this.enemiesDefeated++; // 增加击败敌人计数
        this.game.scoreManager.addScore(100);
        this.game.particleSystem.createParticles(
          enemy.x,
          enemy.y,
          enemy.sprite.color,
          10,
          5,
          5,
          30
        );
      } else if (collisionResult === 'damage') {
        // 玩家受到伤害
        this.game.player.takeDamage();
      }
      
      // 移除屏幕外的敌人
      if (enemy.x + enemy.width < 0) {
        this.enemies.splice(i, 1);
      }
    }
    
    // 生成新敌人，根据当前主题调整
    if (this.enemies.length < Settings.enemies.maxOnScreen && !this.boss) {
      this.enemyTimer++;
      if (this.enemyTimer >= Settings.enemies.spawnInterval) {
        this.enemyTimer = 0;
        
        // 只有在有支持的敌人类型时才生成
        if (this.currentTheme?.enemyTypes?.length > 0) {
          this.spawnEnemy();
        }
      }
    }
  }
  
  spawnEnemy() {
    // 从当前主题中选择敌人类型
    const availableTypes = this.currentTheme?.enemyTypes || ['fox'];
    const selectedType = availableTypes[Math.floor(Math.random() * availableTypes.length)];
    
    // 创建敌人
    try {
      const enemy = new Enemy(this.game, selectedType, {
        x: this.game.canvas.width + 100,
        y: this.game.canvas.height - 150
      });
      this.enemies.push(enemy);
    } catch (error) {
      console.error('生成敌人失败:', error);
    }
  }
  
  render(ctx) {
    // 渲染关卡背景
    this.renderBackground(ctx);
    
    // 渲染所有平台
    for (const platform of this.platforms) {
      platform.render(ctx);
    }
    
    // 如果开启了调试模式，渲染玩家与平台之间的连接线
    if (this.standingPlatform && this.game.debugMode) {
      const player = this.game.player;
      const platform = this.standingPlatform;
      
      ctx.save();
      ctx.strokeStyle = 'rgba(0, 255, 0, 0.8)';
      ctx.lineWidth = 2;
      ctx.setLineDash([5, 3]);
      ctx.beginPath();
      ctx.moveTo(player.x, player.y + player.height);
      ctx.lineTo(player.x, platform.y);
      ctx.stroke();
      
      // 画一个"锚点"在平台上
      ctx.fillStyle = 'rgba(255, 255, 0, 0.8)';
      ctx.beginPath();
      ctx.arc(player.x, platform.y, 4, 0, Math.PI * 2);
      ctx.fill();
      ctx.restore();
    }
    
    // 渲染胡萝卜
    for (const carrot of this.carrots) {
      carrot.render(ctx);
    }
    
    // 渲染Boss
    if (this.boss) {
      this.boss.render(ctx);
    }
    
    // 渲染Boss警告
    if (this.bossWarning) {
      ctx.fillStyle = 'rgba(255, 0, 0, 0.3)';
      ctx.fillRect(0, 0, this.game.canvas.width, this.game.canvas.height);
      
      ctx.fillStyle = '#FF0000';
      ctx.font = '36px Arial';
      ctx.textAlign = 'center';
      ctx.fillText('Boss即将出现!', this.game.canvas.width / 2, this.game.canvas.height / 2);
      ctx.textAlign = 'left';
    }
    
    // 渲染怪物
    for (const enemy of this.enemies) {
      enemy.render(ctx);
    }
    
    // 渲染道具
    this.powerUps.forEach(powerUp => powerUp.render(ctx));
    
    // 渲染关卡信息和目标
    this.renderLevelInfo(ctx);
  }
  
  // 渲染关卡背景
  renderBackground(ctx) {
    // 使用当前主题的背景色
    ctx.fillStyle = this.game.backgroundColor || '#87CEEB';
    ctx.fillRect(0, 0, this.game.canvas.width, this.game.canvas.height);
    
    // 绘制地面
    ctx.fillStyle = this.game.groundColor || '#8B4513';
    ctx.fillRect(0, this.game.canvas.height - 60, this.game.canvas.width, 60);
  }
  
  // 渲染关卡信息和目标
  renderLevelInfo(ctx) {
    ctx.save();
    
    // 显示当前关卡
    ctx.font = '20px Arial';
    ctx.fillStyle = '#FFFFFF';
    ctx.textAlign = 'left';
    ctx.fillText(`关卡 ${this.currentLevel}: ${this.currentTheme?.name || ''}`, 20, 30);
    
    // 显示行进距离
    ctx.fillText(`距离: ${Math.floor(this.distanceTraveled)}米`, 20, 60);
    
    // 显示关卡目标
    if (this.objectives.length > 0) {
      ctx.font = '16px Arial';
      ctx.fillText('目标:', 20, 90);
      
      for (let i = 0; i < this.objectives.length; i++) {
        const obj = this.objectives[i];
        const progress = Math.min(obj.current / obj.target, 1);
        const color = obj.completed ? '#00FF00' : '#FFFFFF';
        
        ctx.fillStyle = color;
        ctx.fillText(
          `- ${obj.description}: ${obj.current}/${obj.target}`,
          20, 120 + i * 25
        );
        
        // 绘制进度条
        ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        ctx.fillRect(220, 112 + i * 25, 100, 8);
        ctx.fillStyle = obj.completed ? '#00FF00' : '#FFA500';
        ctx.fillRect(220, 112 + i * 25, 100 * progress, 8);
      }
    }
    
    ctx.restore();
  }
  
  reset() {
    this.platforms = [];
    this.carrots = [];
    this.boss = null;
    this.currentLevel = 1;
    this.levelTimer = 0;
    this.bossWarning = false;
    this.carrotTimer = 0;
    this.enemies = [];
    this.enemyTimer = 0;
    this.powerUps = [];
    
    // 重置进度数据
    this.resetLevelProgress();
    
    // 重置关卡主题和目标
    this.setCurrentTheme(0);
    this.initLevelObjectives();
    
    // 重新创建初始平台
    this.init();
  }
  
  // 添加新方法：检查道具碰撞
  checkPowerUpCollision(powerUp) {
    return (
      this.game.player.x + this.game.player.width/2 > powerUp.x &&
      this.game.player.x - this.game.player.width/2 < powerUp.x + powerUp.width &&
      this.game.player.y < powerUp.y + powerUp.height &&
      this.game.player.y + this.game.player.height > powerUp.y
    );
  }
  
  // 添加新方法：激活道具效果
  activatePowerUp(powerUp) {
    const config = Settings.powerUps.types[powerUp.type];
    const duration = config.duration;
    
    switch(powerUp.type) {
      case 'doublePoints':
        this.game.player.pointsMultiplier = 2;
        setTimeout(() => {
          this.game.player.pointsMultiplier = 1;
        }, duration * (1000/60));
        break;
        
      case 'shield':
        this.game.player.hasShield = true;
        setTimeout(() => {
          this.game.player.hasShield = false;
        }, duration * (1000/60));
        break;
        
      case 'magnet':
        this.game.player.hasMagnet = true;
        this.game.player.magnetRange = config.range;
        setTimeout(() => {
          this.game.player.hasMagnet = false;
          this.game.player.magnetRange = 0;
        }, duration * (1000/60));
        break;
    }
    
    // 显示道具效果提示
    this.game.floatingTexts.push({
      content: `获得${config.name}！`,
      x: powerUp.x,
      y: powerUp.y - 30,
      color: config.sprite.color,
      alpha: 1,
      velocity: -2
    });
    
    // 创建特效
    this.game.particleSystem.createParticles(
      powerUp.x + powerUp.width/2,
      powerUp.y + powerUp.height/2,
      config.sprite.color,
      15,
      5,
      5,
      30
    );
  }
  
  // 更新道具
  updatePowerUps() {
    // 更新现有道具
    for (let i = this.powerUps.length - 1; i >= 0; i--) {
      const powerUp = this.powerUps[i];
      if (powerUp.update()) {
        // 如果返回true，表示道具被收集，需要移除
        this.powerUps.splice(i, 1);
      }
    }
    
    // 随机生成新道具（每180帧可能生成一个）
    if (this.game.gameTime % Settings.powerUps.spawnInterval === 0 && 
        this.powerUps.length < 3 && 
        Math.random() < 0.2 && 
        !this.boss) {
      
      // 获取可用道具类型
      const availableTypes = Object.keys(Settings.powerUps.types);
      // 根据几率随机选择一种类型
      let selectedType = null;
      const totalChance = Object.values(Settings.powerUps.types).reduce(
        (sum, config) => sum + (config.chance || 0.1), 0);
      
      let random = Math.random() * totalChance;
      for (const type of availableTypes) {
        const config = Settings.powerUps.types[type];
        random -= (config.chance || 0.1);
        if (random <= 0) {
          selectedType = type;
          break;
        }
      }
      
      if (selectedType) {
        try {
          // 创建新道具 - 位置在屏幕右侧随机高度
          const powerUp = new Powerup(
            this.game,
            selectedType,
            this.game.canvas.width + 50,
            Math.random() * (this.game.canvas.height - 200) + 100
          );
          this.powerUps.push(powerUp);
        } catch (error) {
          console.error('创建道具失败:', error);
        }
      }
    }
  }
} 